package com.engine.jucailinkq.attendance.attendanceanalysis.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cloudstore.dev.api.util.EMManager;
import com.engine.jucailinkq.common.util.ApiReturnTools;
import com.engine.common.util.ParamUtil;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.dateformat.DateTransformer;
import weaver.dateformat.TimeZoneVar;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.hrm.resource.ResourceComInfo;
import weaver.systeminfo.SystemEnv;

@Slf4j
@Path("/hrm/kq/jucailin/button")
public class AttendanceJucailinButtonAction {

    private DateTimeFormatter fullFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 将所有的企业日历取消默认值标记
     */
    @POST
    @Path("/getButtonBaseInfo")
    @Produces(MediaType.TEXT_PLAIN)
    public String getButtonBaseInfo(@Context HttpServletRequest request, @Context HttpServletResponse response){
        Map<String, Object> retmap = new HashMap<String, Object>();
        User user = HrmUserVarify.getUser (request , response) ;
        try {
            ResourceComInfo resourceComInfo = new ResourceComInfo();
            String lastname = user.getLastname();
            String messagerurl = resourceComInfo.getMessagerUrls("" + user.getUID());
            String shortname = "";

            boolean USERICONLASTNAME = Util.null2String(new BaseBean().getPropValue("Others", "USERICONLASTNAME")).equals("1");
            if (USERICONLASTNAME && (messagerurl.indexOf("icon_w_wev8.jpg") > -1 || messagerurl.indexOf("icon_m_wev8.jpg") > -1 || messagerurl.indexOf("dummyContact.png") > -1)) {
                shortname = User.getLastname(Util.null2String(Util.formatMultiLang(lastname, "" + user.getLanguage())));
            }
            String curDate = DateUtil.getCurrentDate();

            retmap.put("userid", user.getUID());
            retmap.put("lastname", lastname);
            retmap.put("shortname", shortname);
            retmap.put("messagerurl", messagerurl);

            retmap.put("date", curDate);
            retmap.put("timemillis", System.currentTimeMillis());

            retmap.put("status", "1");
        } catch (Exception e) {
            log.error("execute fail,catch error: [{}]",e);
            retmap.put("status", "-1");
            return ApiReturnTools.error("500",SystemEnv.getHtmlLabelName(382661, user.getLanguage()));
        }
        return JSONObject.toJSONString(retmap);
    }

    /**
     * 获取签到签退按钮
     * 以及考勤流程数据
     * 以及上次签到时间
     * @param request
     * @param response
     * @return
     */
    @POST
    @Path("/getButtons")
    @Produces(MediaType.TEXT_PLAIN)
    public String getButtons(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        Map<String, Object> retmap = new HashMap<String, Object>();
        User user = HrmUserVarify.getUser (request , response) ;
        try{
            LocalDateTime now = LocalDateTime.now();
            String curDate = DateUtil.getCurrentDate();
            //真正的考勤时间线
            ResourceComInfo resourceComInfo = new ResourceComInfo();

            String lastname = user.getLastname();
            String messagerurl = resourceComInfo.getMessagerUrls(""+user.getUID());
            String shortname = "";

            boolean USERICONLASTNAME = Util.null2String(new BaseBean().getPropValue("Others" , "USERICONLASTNAME")).equals("1");
            if(USERICONLASTNAME&&(messagerurl.indexOf("icon_w_wev8.jpg")>-1||messagerurl.indexOf("icon_m_wev8.jpg")>-1||messagerurl.indexOf("dummyContact.png")>-1)){
                shortname = User.getLastname(Util.null2String(Util.formatMultiLang(lastname, ""+user.getLanguage())));
            }
            String resourceId = String.valueOf(user.getUID());

            List<Object> signListLine = getSignListLine(resourceId,curDate);

            retmap.put("lastname", lastname);
            retmap.put("shortname", shortname);
            retmap.put("messagerurl", messagerurl);
            retmap.put("date", curDate);
            retmap.put("timeline", signListLine);
            retmap.put("status", "1");
            retmap.put("now", now.format(fullFormatter));

        }catch (Exception e) {
            retmap.put("status", "-1");
            retmap.put("message",  SystemEnv.getHtmlLabelName(382661,user.getLanguage()));
        }
        return JSONObject.toJSONString(retmap);
    }

    /**
     * 针对非工作时间的签到签退
     */
    private List<Object> getSignListLine(String resourceId, String curDate) {
        List<Object> signListLine = Lists.newArrayList();
        RecordSet recordSet = new RecordSet();
        String sql = "select * from hrmschedulesign where userid = "+resourceId+" and signDate='"+curDate+"' order by signTime desc ";
        recordSet.executeQuery(sql);
        while (recordSet.next()){
            String signDate = recordSet.getString("signDate");
            String signTime = recordSet.getString("signTime");
            String signDateTime = signDate+" "+signTime;
            String addr = Util.null2String(recordSet.getString("addr"));
            Map<String,Object> cardTimelineMap = new HashMap<>();
            cardTimelineMap.put("date", curDate);
            cardTimelineMap.put("signTime", signDateTime);
            cardTimelineMap.put("position", addr);
            signListLine.add(cardTimelineMap);
        }
        return signListLine;
    }

    /**
     * 签到签退
     * @param request
     * @param response
     * @return
     */
    @POST
    @Path("/punchButton")
    @Produces(MediaType.TEXT_PLAIN)
    public String punchButton(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        Map<String, Object> retmap = new HashMap<String, Object>();
        User user = HrmUserVarify.getUser (request , response) ;
        try{
            Map<String, Object> params = ParamUtil.request2Map(request);
            RecordSet rs = new RecordSet();
            String deviceInfo = Util.null2String(params.get("deviceInfo"));
            JSONObject jsonObject = null;
            if(deviceInfo.length() > 0){
                jsonObject = JSON.parseObject(deviceInfo);
                JSONObject jsonObject1 = new JSONObject();
                Set<Entry<String, Object>> jsonSet =  jsonObject.entrySet();
                for(Entry<String, Object> js : jsonSet){
                    String key = js.getKey();
                    String value = Util.null2String(js.getValue());
                    jsonObject1.put(key, value);
                }
                if(!jsonObject1.isEmpty()){
                    deviceInfo = jsonObject1.toJSONString();
                }
            }

            //手机打卡部分
            String longitude = Util.null2String(params.get("longitude"));
            String latitude = Util.null2String(params.get("latitude"));
            String signData = Util.null2String(params.get("signData"));

            //wifi用的
            String mac = Util.null2String(params.get("mac"));
            String sid = Util.null2String(params.get("sid"));
            String addr = Util.null2String(params.get("position"));
            String showaddress =addr;
            String ismobile = Util.null2String(params.get("ismobile"));
            //区分是来自于钉钉还是EM7
            String browser = Util.null2String(params.get("browser"));

            DateTimeFormatter fullFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
            LocalTime localTime = LocalTime.now();
            String signTime =localTime.format(dateTimeFormatter);
            String signDate = LocalDate.now().format(dateFormatter);

            String timeZone = Util.null2String(TimeZoneVar.getTimeZone(),"");
            //处理多时区
            String timeZoneConversion = Util.null2String(new weaver.general.BaseBean().getPropValue("weaver_timezone_conversion","timeZoneConversion")).trim();
            if("1".equals(timeZoneConversion)) {
                DateTransformer dateTransformer=new DateTransformer();
                String[] zone_localTime = dateTransformer.getLocaleDateAndTime(signDate,signTime);
                if(zone_localTime != null && zone_localTime.length == 2){
                    signDate = zone_localTime[0];
                    signTime = zone_localTime[1];
                }
            }

            int userId = user.getUID();
            String userType = user.getLogintype();
            String clientAddress = Util.getIpAddr(request);
            String isInCom = "1";

            String datetime_timezone = signDate+" "+signTime;
            LocalDateTime nowDateTime = LocalDateTime.parse(datetime_timezone,fullFormatter);

            //记录下是来自于E9的pc端签到
            String signfrom = "e9pc";
            if("1".equalsIgnoreCase(ismobile)){
                signfrom = "e9mobile";
                if("DingTalk".equalsIgnoreCase(browser)){
                    signfrom = "DingTalk";
                }else if("Wechat".equalsIgnoreCase(browser)){
                    signfrom = "Wechat";
                    String weChat_deviceid = Util.null2String(request.getSession().getAttribute(
                            EMManager.DeviceId));
                    if(weChat_deviceid.length() > 0){
                        //微信打卡的设备号需要单独处理
                        if(jsonObject != null){
                            jsonObject.put("deviceId", weChat_deviceid);
                        }else{
                            jsonObject = new JSONObject();
                            jsonObject.put("deviceId", weChat_deviceid);
                        }
                        if(!jsonObject.isEmpty()){
                            deviceInfo = jsonObject.toJSONString();
                        }
                    }
                }
            }

            deviceInfo = deviceInfo.replaceAll("\\?", "");
            String signType = "1";
            String belongdate = signDate;
            String punchSql = "insert into HrmScheduleSign(userId,userType,signType,signDate,signTime,clientAddress,isInCom,timeZone,belongdate,signfrom,longitude,latitude,addr,deviceInfo,showaddress) "+
                    " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
            boolean isOk = rs.executeUpdate(punchSql,userId,userType,signType,signDate,signTime,clientAddress,isInCom,
                    timeZone,belongdate,signfrom,longitude,latitude,addr,deviceInfo,showaddress);
            log.debug(user.getLastname()+":PunchButtonCmd:punchSql:"+punchSql+":isOk:"+isOk);

            retmap.put("status", "1");
            retmap.put("signdate", signDate);
            retmap.put("signtime", signTime);
        }catch (Exception e){
            retmap.put("status", "-1");
            retmap.put("message",  SystemEnv.getHtmlLabelName(382661,user.getLanguage()));
        }
        return JSONObject.toJSONString(retmap);
    }
}
